package cn.wolfcode.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;

import cn.wolfcode.domain.Article;
import cn.wolfcode.domain.ArticleContent;
import cn.wolfcode.domain.ArticleType;
import cn.wolfcode.domain.UserInfo;
import cn.wolfcode.service.IArticleService;
import cn.wolfcode.service.IArticleTypeService;
import cn.wolfcode.service.IUserInfoService;
import cn.wolfcode.utils.UrlUtil;
import cn.wolfcode.vo.AuthAccessTokenVo;

@Controller
@RequestMapping(value="/wechat")
public class WechatHomeController {

	@Autowired
	private IArticleTypeService articleTypeService;
	
	@Autowired
	private IArticleService articleService;
	
	
	@Autowired
	private IUserInfoService userInfoService;
	
	
	@Autowired
	private RestTemplate restTemplate;
	
	
	@Value("${wechat.apid}")
	private String appId;
	
	@Value("${wechat.appsecret}")
	private String secret;
	
	@Value("${wechat.baseUrl}")
	private String baseUrl;
	
	/**
	 * 微信端的首页
	 */
	@RequestMapping(value="/index")
	public String index(Model model) {
		//获取所有文章分类
		List<ArticleType> articleTypeList = articleTypeService.getArticleTypeList();
		model.addAttribute("articelTypeList", articleTypeList);
		return "wechat/index";
	}
	
	/**
	 * 通过文章分类的编码，获取该文章分类下的文章列表
	 */
	@RequestMapping(value="/articleList")
	public String getArticleList(String articleType,Model model) {
		//通过文章分类编码查询出对应的文章分类对象
		ArticleType type = articleTypeService.getArticleTypeByCode(articleType);
		model.addAttribute("articleType", type);
		
		//通过文章分类编码查询出该文章分类下的文章列表
		List<Article> articleList = articleService.getArticleByCode(articleType);
		model.addAttribute("articleList", articleList);
		return "wechat/article_list";
	}
	
	
	/**
	 * 通过文章的ID，获取该文章对像
	 */
	@RequestMapping(value="/articleDetail")
	public String getArticleDetail(Long id,Model model) {
		Article article = articleService.getArticle(id);
		model.addAttribute("article", article);
		//阅读人数加1
		article.setCount(article.getCount() + 1);
		articleService.save(article);
		return "wechat/article_detail";
	}
	
	/**
	 * 通过文章ID获取该文章的内容
	 */
	@RequestMapping(value="/articleContent")
	@ResponseBody
	public String getArticleContent(Long id) {
		
		ArticleContent articleContent = articleService.getContent(id);
		return articleContent.getContent();
	}
	
	/***
	 * 微信端的个人中心界面
	 */
	@RequestMapping(value="/userCenter")
	public String userCenter(HttpSession session) {
		//获取用户在session中保持的用户相关信息
		UserInfo userInfo = (UserInfo)session.getAttribute("userInfo");
		//判断session中用户信息对象是否为null，如果为null，就需要做微信授权登录
		if(userInfo == null) {
			//把用户需要访问的资源路径存到session中
			session.setAttribute("accessUrl", "/wechat/userCenter");
			return "redirect:"+UrlUtil.AUTH_URL
					.replace("APPID", appId)
			.replace("REDIRECT_URI", baseUrl+"/wechat/login")
			.replace("SCOPE","snsapi_userinfo")
			;
		}
		//否则，进入个人中心界面
		else {
			return "wechat/user_center";
		}
	}
	
	/**
	 * 回调地址
	 */
	@RequestMapping(value="/login")
	public String login(String code,HttpSession session) {
		
		String result = restTemplate.getForObject(UrlUtil.GET_AUTH_ACCESS_TOKEN_RUL
									.replace("APPID", appId)
									.replace("SECRET",secret)
									.replace("CODE",code)
				                  , String.class);
		AuthAccessTokenVo authAccessToken = JSON.parseObject(result, AuthAccessTokenVo.class);
		
		//通过openID获取对应的用户（UserInfo）
		UserInfo userInfo = userInfoService.getUserInfoByOpenId(authAccessToken.getOpenid());
		//如果获取到的UserInfo对象是null，则调用拉取用户信息的接口,并且把拉取到的用户信息，插入到我们自己的数据
		if(userInfo == null) {
			String userInfoJson = restTemplate.getForObject(UrlUtil.GET_USER_INFO_URL
					.replace("ACCESS_TOKEN", authAccessToken.getAccess_token())
					.replace("OPENID", authAccessToken.getOpenid())
					,String.class);

			userInfo = JSON.parseObject(userInfoJson, UserInfo.class);
			
			userInfoService.save(userInfo);
		}
		//否则，直接把从自己数据库获取到的UserInfo对象设置到session中
		session.setAttribute("userInfo", userInfo);
		
		//用户登录前需要访问的资源路径
		String accessUrl = (String)session.getAttribute("accessUrl");
		return "redirect:"+accessUrl;
	}
}













